const {
	Controller
} = require('egg');

const fs = require('fs');
const path = require('path');

class UploadController extends Controller {
	constructor(ctx, app) {
		super(ctx, app); // 如果需要在构造函数做一些处理，一定要有这句话，才能保证后面 `this.ctx`的使用。
		// 就可以直接通过 this.ctx 获取 ctx 了
		// 还可以直接通过 this.app 获取 app 了
	}

	resultsuccess(data, message) {
		return this.ctx.body = {
			success: true,
			code: 200,
			message: message || '操作成功',
			data: data
		};
	}
	resultfail(message, code) {
		return this.ctx.body = {
			success: false,
			code: code || 300,
			message: message || '操作失败',
		};
	}



	async uploads() {
		const file = this.ctx.request.files[0];
		try {
			const filename = 'uploads/' + file.filename; // 假设你的上传文件夹叫 uploads
			const fileData = fs.readFileSync(file.filepath);
			const date = Date.now(); // 毫秒数
			//设置文件保存路径
			const tempDir = path.join('app/public/uploads',date + path.extname(file.filename)); // 返回文件保存的路径
			// console.log('毫秒数 extname', date, path.extname(file.filename));
			// 写入文件夹
			fs.writeFileSync(tempDir, fileData);
			this.resultsuccess('http://127.0.0.1:7001/public/uploads/' + date + path.extname(file.filename))
		} catch (error) {
			this.resultfail(error)
		}
	}
}

module.exports = UploadController;